﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using CSJ2K.Util.IO;

namespace CSJ2K.Jpc.Segments
{
    /// <summary>Start of tile-part (SOT)</summary>
    /// <comment>
    /// Function: Marks the beginning of a tile-part, the index of its tile, and the index of 
    ///      its tile-part. The tile-parts of a given tile shall appear in order (see TPsot)
    ///      in the codestream. However, tile-parts from other tiles may be interleaved in the 
    ///      codestream. Therefore, the tile-parts from a given tile may not appear contiguously
    ///      in the codestream. 
    /// Usage: Every tile-part header. Shall be the first marker segment in a tile-part header. 
    ///      There shall be at least one SOT in a codestream. There shall be only one SOT per 
    ///      tile-part. 
    /// Length: Fixed.
    /// </comment>
    public class SOT : Segment 
    {
        /// <summary>Tile index.  This number refers to the tiles in raster order starting at number 0.</summary>
        public ushort I;

        /// <summary>
        /// Length, in bytes, from the beginning of the first byte of this SOT marker segment
        /// to the end of the data of that tile-part. If 0, tile-part is assumed to contain all
        /// data until the EOC marker.
        /// </summary>
        public uint P; 
     
        /// <summary>Tile-part index.</summary>
        public byte TP;

        /// <summary>Number of tile-parts of a tile in the codestream.  0 means not specified.</summary>
        public byte TN;


        public SOT(Stream source)
            : this(source, (Markers)StreamUtil.ReadBUInt16(source)) { }
        public SOT(Stream source, Markers marker)
            : base(source, marker, true)
        {
            if (marker != Markers.SOT) throw (new ApplicationException("Attempting to create segment of the wrong type."));

            I = StreamUtil.ReadBUInt16(source);
            Debug.WriteLine("Tile Index: " + I);
            P = StreamUtil.ReadBUInt32(source);
            Debug.WriteLine("Length: " + P);
            TP = StreamUtil.ReadOctet(source);
            Debug.WriteLine("Tile-part Index: " + TP);
            TN = StreamUtil.ReadOctet(source);
            Debug.WriteLine("Number of Tile-parts in Tile: " + TN);
        }
    }
}
